<?php
set_include_path ( $_SERVER ['DOCUMENT_ROOT'] );
include_once 'admin/includes/functions/admin-functions.php';
global $DBobject, $CONFIG, $SMARTY;

$error = array();
$error['post'] = "Session has expired. Please refresh.";
$referer = parse_url($_SERVER['HTTP_REFERER']);
if( $referer['host'] == $GLOBALS['HTTP_HOST'] && checkToken('admin', $_POST["formToken"])){
	$response = false;
	$url = false;
	
	switch ($_POST['action']) {

		case 'NewPost':
		case 'NewReply': 
			if ($_FILES["file"]["error"] == 0){
				if (($_FILES["file"]["type"] == "image/gif" )|| ($_FILES["file"]["type"] == "image/jpeg" )||($_FILES["file"]["type"] == "image/png" ) || (strtolower(substr($_FILES["file"]["name"], -3))=='gif') || (strtolower(substr($_FILES["file"]["name"], -3))=='jpg') || (strtolower(substr($_FILES["file"]["name"], -4))=='jpeg') || (strtolower(substr($_FILES["file"]["name"], -3))=='png')){
					$path =  $_SERVER ['DOCUMENT_ROOT'];
					$file_short = time().'_'.preg_replace("/[^a-zA-Z0-9_.]/", "", $_FILES["file"]["name"]);
					$listing_image = "/uploads/noticeboard/" .$file_short;
					$file_name = $path . $listing_image;
					if(!move_uploaded_file($_FILES["file"]["tmp_name"],$file_name)){
						$error = "The uploaded file cannot be saved.";
						$error = ($_POST['action'] == 'NewReply')?array('reply'=>$error, 'object_id'=>$_POST['listing_parent_id']):array('post'=>$error);
						break;
					}
				}else{
					$error = "The uploaded file does not match the approved file types.";
					$error = ($_POST['action'] == 'NewReply')?array('reply'=>$error, 'object_id'=>$_POST['listing_parent_id']):array('post'=>$error);
					break;
				}
			}
			try{
				$sql = "INSERT INTO tbl_sequence VALUES ()";
				$DBobject->wrappedSql($sql);
				$objID = $DBobject->wrappedSqlIdentity();
				if(!empty($objID)){
					$listing_parent_id = ($_POST['action'] == 'NewReply')?$_POST['listing_parent_id']:0;
					$sql = "INSERT INTO tbl_messageboard (listing_object_id, listing_type_id, listing_parent_id, listing_name, listing_seo_title,
													listing_content1, listing_image, listing_published, listing_created)
									VALUES (:listing_object_id, 9, :listing_parent_id, :listing_name, :listing_seo_title,
													:listing_content1, :listing_image, 1, now() )";
					$params  = array(
							":listing_object_id"=>$objID,
							":listing_parent_id"=>$listing_parent_id,
							":listing_name"=>$_SESSION['user']['admin']['id'],
							":listing_seo_title"=>$_SESSION['user']['admin']['name'] . " " . $_SESSION['user']['admin']['surname'],
							":listing_content1"=>$_POST['listing_content1'],
							":listing_image"=>$listing_image
					);
					$DBobject->wrappedSql($sql, $params);
					 
					if(!empty($_POST['tags'])){
						$sql = "INSERT INTO tbl_tag (tag_object_table, tag_object_id, tag_value, tag_created) VALUES ('tbl_messageboard', :objId, :value, now() )";
						$tags = explode(',', $_POST['tags']);
						foreach ($tags as $tag){
							$value = trim($tag);
							if(!empty($value)){
								$DBobject->wrappedSql($sql, array(':objId'=> $objID, ':value'=> $value));
							}
						}
					} 
					$error = null;
				}
			}catch (Exception $e){
				$error = ($_POST['action'] == 'NewReply')?array('reply'=>$e, 'object_id'=>$_POST['listing_parent_id']):array('post'=>$e);
				break;
			}  
			
				
			if($_POST['action'] == 'NewPost'){ //SEND EMAIL - ONLY NEW POST 
				try {
					$sql = "SELECT DISTINCT(admin_email) FROM tbl_admin WHERE admin_deleted IS NULL AND admin_level < 3";
					if ($res2 = $DBobject->wrappedSql($sql)){
						$recipients = array();
						foreach ($res2 as $r){
							$recipients[] = $r['admin_email'];
						}
						$subject = "A new post has been published on the noticeboard";
						$from = (string) $CONFIG->company->name;
						$fromEmail = 'noreply@'. str_replace('www.', '', $GLOBALS['HTTP_HOST']);
						$COMP = json_encode($CONFIG->company);
						$SMARTY->assign('COMPANY', json_decode($COMP,TRUE));
						$SMARTY->assign('DOMAIN', "http://" . $GLOBALS['HTTP_HOST']);
						$SMARTY->assign('message', $_POST['listing_content1']);
						$SMARTY->assign('image', $listing_image);
						$SMARTY->assign('admin', $_SESSION['user']['admin']['name'] . " " . $_SESSION['user']['admin']['surname']);
						$body = $SMARTY->fetch('email-new-post-noticeboard.tpl');
						createBulkMail($recipients, $from, $fromEmail, $subject, $body, $_SESSION['user']['admin']['id']);
						$response = sendBulkMail();
					}
				} catch (Exception $e) {}
				
			}
			$_SESSION['post'] = ($_POST['action'] == 'NewReply')?array('replied_to'=>$_POST['listing_parent_id']):array();
			$_SESSION['notice'] = "Your message/question has been published!";
			header("Location: ".$_SERVER['HTTP_REFERER']."#notice");
			die();
	
		case 'GetReplyPostForm':
			$SMARTY->assign('token', $_POST["formToken"]);
			$SMARTY->assign('listing_parent_id', $_POST['listing_parent_id']);
			$template = $SMARTY->fetch('reply-form.tpl');
			echo json_encode(array(
					"error" => null,
					"success" => true,
					"template" => $template
			));
			die();
			
		case 'DeletePost':
			$sql = "UPDATE tbl_messageboard SET listing_deleted = now() WHERE listing_deleted IS NULL AND listing_type_id = '9' AND (listing_object_id = :object_id OR listing_parent_id = :object_id)";
			$res = $DBobject->wrappedSql($sql, array(":object_id"=>$_POST['listing_object_id']));
			echo json_encode(array(
					"error" => null,
					"success" => $res
			));
			die();
			
	}
}
$_SESSION['post'] = $_POST;
$_SESSION['error']= $error;
header("Location: ".$_SERVER['HTTP_REFERER']."#error");
die();
